package com.wedimob.boxinternetprotection.freebox;

import java.util.Timer;
import java.util.TimerTask;

import android.util.Log;

public class Refresher {

    public Refresher(Freebox freebox) {
        super();
        this.freebox = freebox;
    }

    private static final String CLASS_TAG = Refresher.class.getName();

    private Freebox freebox;
    private boolean isAutoRefresh = false;
    private Timer timer = new Timer();
    private RefreshTask task = new RefreshTask();
    private int frequency;

    private class RefreshTask extends TimerTask {
        @Override
        public void run() {
            if (isAutoRefresh && freebox.isConnected()) {
                Log.i(CLASS_TAG, "Refresh freebox server");
                freebox.refreshBox();
                Log.i(CLASS_TAG, "Refresh freebox clients");
                freebox.refreshClients();
            }
            else {
                Log.i(CLASS_TAG, "Refresh freebox - not connected");
            }
        }
    };

    public void setAutoRefresh(int freqency) {
        if (isAutoRefresh) {
            timer.cancel();
            timer.purge();
            task.cancel();
            timer = new Timer();
            task = new RefreshTask();
        }

        this.frequency = freqency;
        isAutoRefresh = true;
        timer.schedule(task, 1000, 1000 * freqency);
    }

    public void cancelAutoRefresh() {
        if (isAutoRefresh) {
            timer.cancel();
            timer.purge();
            task.cancel();
            timer = new Timer();
            task = new RefreshTask();
        }
        isAutoRefresh = false;
    }

    @Override
    protected void finalize() throws Throwable {
        cancelAutoRefresh();
        super.finalize();
    }

    public void resumeAutoRefresh() {
        setAutoRefresh(this.frequency);
    }
}
